package tw.asap.plus.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import tw.asap.plus.R;
import tw.asap.plus.common.ConstValue;
import tw.asap.plus.entity.CartBean;
import tw.asap.plus.entity.User;
import tw.asap.plus.entity.request.CommonRequestParams;
import tw.asap.plus.entity.request.OrderCreateResult;
import tw.asap.plus.entity.response.Address;
import tw.asap.plus.entity.response.OrderCreate;
import tw.asap.plus.entity.response.ResponseDataWrapper;
import tw.asap.plus.entity.response.ShopIndex;
import tw.asap.plus.network.config.HRetrofitCreator;
import tw.asap.plus.network.service.OrderService;
import tw.asap.plus.network.service.UserService;
import tw.asap.plus.ui.AsapBaseActivity;
import tw.asap.plus.ui.custom.AppBar;
import tw.asap.plus.ui.custom.SimpleGoodsItem;
import tw.asap.plus.utils.SPUtil;
import tw.asap.plus.utils.ScreenUtil;
import tw.asap.plus.utils.Toaster;
import tw.asap.plus.utils.Utils;

/**
 * Created by Yax.
 * Date: 15/11/13
 * Time: 下午11:41
 * Description:
 */
public class OrderConfirmActivity extends AsapBaseActivity implements View.OnClickListener {


    @InjectView(R.id.appbar)
    AppBar appbar;
    @InjectView(R.id.view_choose_address)
    TextView viewChooseAddress;
    @InjectView(R.id.checkbox_cod)
    CheckBox checkboxCod;
    @InjectView(R.id.rl_cod)
    RelativeLayout rlCod;
    @InjectView(R.id.checkbox_online)
    CheckBox checkboxOnline;
    @InjectView(R.id.rl_pay_online)
    RelativeLayout rlPayOnline;
    @InjectView(R.id.ll_pay_choose)
    LinearLayout llPayChoose;
    @InjectView(R.id.ll_goods_list)
    LinearLayout llGoodsList;
    @InjectView(R.id.tv_amt_detail)
    TextView tvAmtDetail;
    @InjectView(R.id.tv_confirm)
    TextView tvConfirm;
    @InjectView(R.id.ll_content)
    LinearLayout llContent;
    @InjectView(R.id.tv_total_amt)
    TextView tvTotalAmt;
    @InjectView(R.id.rl_summery)
    RelativeLayout rlSummery;
    @InjectView(R.id.bt_add_memo)
    TextView btAddMemo;

    public static final int REQUEST_ADD_MEMO = 10;

    private ArrayList<CartBean> cartBeans;
    private ShopIndex.ShopEntity shopEntity;

    Address currentAddress = null;
    private ArrayList<Address> addresses = null;

    View defaultAddress = null;
    private String memo = "";

    int totalAmt = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_order_confirm);
        ButterKnife.inject(this);
        tvConfirm.setOnClickListener(this);
        cartBeans = getIntent().getParcelableArrayListExtra("GOODS_LIST");
        shopEntity = getIntent().getParcelableExtra("SHOP_ENTITY");
        initView();

        if (User.hasLogin()) {
            getAddressInfo();
        } else {
            startActivityForResult(new Intent(this, LoginAsapActivity.class), RESULT_FIRST_USER);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_FIRST_USER:
                if (resultCode == RESULT_OK) {
                    getAddressInfo();
                } else {
                    finish();
                }
                break;
            case AddressListActivity.ADDRESS_CHOOSE:
            case AddressListActivity.ADDRESS_NEW:
                if (resultCode == RESULT_OK && data != null) {
                    Address temp = data.getParcelableExtra("ADDRESS");
                    if (temp != null) {
                        currentAddress = temp;
                        fillAddress();
                    }
                }
                break;
            case REQUEST_ADD_MEMO:
                if (resultCode == RESULT_OK) {
                    memo = data.getStringExtra("MEMO");
                    if (!TextUtils.isEmpty(memo))
                        btAddMemo.setText(memo);
                }
                break;
        }
    }


    private void getAddressInfo() {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<List<Address>>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<List<Address>>> subscriber) {
                UserService service = creator.getService(UserService.class);
                subscriber.onNext(service.getAddress(new CommonRequestParams()));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<List<Address>>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseDataWrapper<List<Address>> addressList) {
                        if (addressList.respcd.equals(ConstValue.RESPCD)) {
                            initAddressLayout(addressList.data);
                            addresses = new ArrayList<>();
                            addresses.addAll(addressList.data);
                        } else {
                            Toaster.s(OrderConfirmActivity.this, addressList.respmsg);
                        }
                    }
                });
    }

    private void initAddressLayout(List<Address> addressList) {
        if (addressList != null && addressList.size() > 0) {
            for (Address address1 : addressList) {
                if (address1.getIs_default().equals("1")) {
                    currentAddress = address1;
                }
            }
            if (currentAddress == null) {
                currentAddress = addressList.get(0);
            }
            fillAddress();
        } else {
            viewChooseAddress.setVisibility(View.VISIBLE);
            viewChooseAddress.setOnClickListener(this);
        }
    }

    private void fillAddress() {
        viewChooseAddress.setVisibility(View.GONE);
        if (defaultAddress == null) {
            defaultAddress = LayoutInflater.from(this).inflate(R.layout.item_address, null);
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(0, ScreenUtil.dip2px(this, 12), 0, 0);
            llContent.addView(defaultAddress, 0, layoutParams);
        }
        ((TextView) defaultAddress.findViewById(R.id.tv_name)).setText(currentAddress.getName());
        ((TextView) defaultAddress.findViewById(R.id.tv_mobile)).setText(currentAddress.getMobile());
        defaultAddress.findViewById(R.id.ic_default).
                setVisibility(currentAddress.getIs_default().equals("1") ? View.VISIBLE : View.GONE);
        ((TextView) defaultAddress.findViewById(R.id.tv_address)).setText(currentAddress.getArea().concat(currentAddress.getAddress()));
        defaultAddress.findViewById(R.id.edit).setOnClickListener(this);
    }


    private void initView() {
        appbar.setLeftClickEvent(v -> finish());
        for (CartBean cartBean : cartBeans) {
            SimpleGoodsItem goodsItem = new SimpleGoodsItem(this);
            goodsItem.setGoodsInfo(cartBean);
            llGoodsList.addView(goodsItem);
            int num = Integer.parseInt(cartBean.item_nums);
            int price = Integer.parseInt(cartBean.goodsInfo.itemEntity.getPrice());
            totalAmt += (num * price);
        }
        String deliveryAmt = Utils.getFormatAmt(shopEntity.getShipping_price());
        tvAmtDetail.setText("商品金额 $".concat(Utils.getFormatAmt(String.valueOf(totalAmt)))
                .concat(" + 配送费 $").concat(deliveryAmt));
        int acturlAmt = Integer.parseInt(shopEntity.getShipping_price()) + totalAmt;
        tvTotalAmt.setText("还需支付 $".concat(Utils.getFormatAmt(String.valueOf(acturlAmt))));
    }

    private void createOrder() {
        HRetrofitCreator creator = HRetrofitCreator.getInstance();
        Observable.create(new Observable.OnSubscribe<ResponseDataWrapper<OrderCreateResult>>() {
            @Override
            public void call(Subscriber<? super ResponseDataWrapper<OrderCreateResult>> subscriber) {
                OrderService service = creator.getService(OrderService.class);
                String lat = SPUtil.getInstance(OrderConfirmActivity.this).getString(ConstValue.Sp.LAT, "0");
                String lng = SPUtil.getInstance(OrderConfirmActivity.this).getString(ConstValue.Sp.LNG, "0");
                OrderCreate order = new OrderCreate();
                order.setAddr_id(currentAddress.getAddrid());
                order.setCartBeans(cartBeans);
                order.setOrder_lat(lat);
                order.setOrder_lng(lng);
                order.setOrder_memo(memo);
                order.setShopkey(shopEntity.getShopkey());
                subscriber.onNext(service.createOrder(order));
                subscriber.onCompleted();
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<ResponseDataWrapper<OrderCreateResult>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseDataWrapper<OrderCreateResult> orderCreateResult) {
                        if (orderCreateResult.respcd.equals(ConstValue.RESPCD)) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(OrderConfirmActivity.this);
                            builder.setMessage(getString(R.string.create_order_success));
                            builder.setTitle("提示");
                            builder.setPositiveButton("OK", (dialog, which) -> {
                                MainActivity.REFRESH_ORDER_LIST = 1;
                                Intent intent = new Intent(OrderConfirmActivity.this, OrderDetailActivity.class);
                                intent.putExtra("ORDER_SN", orderCreateResult.data.getOrder_sn());
                                startActivity(intent);
                            }).show();
                        }else{
                            AlertDialog.Builder builder = new AlertDialog.Builder(OrderConfirmActivity.this);
                            builder.setTitle("提示");
                            builder.setMessage(orderCreateResult.respmsg);
                            builder.setPositiveButton("OK", (dialog, which) -> {
                                finish();
                            }).show();
                        }
                    }
                });
    }

    @OnClick(R.id.bt_add_memo)
    public void addMemo() {
        Intent intent = new Intent(this, MemoActivity.class);
        intent.putExtra("MEMO", memo);
        startActivityForResult(intent, REQUEST_ADD_MEMO);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.edit:
                Intent intent = new Intent(OrderConfirmActivity.this, AddressListActivity.class);
                intent.putExtra("ADDRESS_ID", currentAddress.getAddrid());
                startActivityForResult(intent, AddressListActivity.ADDRESS_CHOOSE);
                break;

            case R.id.view_choose_address:
                Intent newAddress = new Intent(OrderConfirmActivity.this, AddressListActivity.class);
                startActivityForResult(newAddress, AddressListActivity.ADDRESS_NEW);
                break;

            case R.id.tv_confirm:
                if (currentAddress == null) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(OrderConfirmActivity.this);
                    builder.setTitle("提示");
                    builder.setMessage(getString(R.string.please_set_address));
                    builder.setPositiveButton("OK", (dialog, which) -> {
                    }).show();
                    return;
                } else {
                    createOrder();
                }
                break;
        }
    }


}
